<template>
    <div class="centered-container">
        <div class="main-wrapper">
            <!-- 用户操作按钮 -->
            <div class="left-sidebar">
                <div class="user-name">{{ currentUser }}</div>
                <button type="button" @click="createGroup">创建群聊</button>
                <button type="button" @click="joinGroup">加入群聊</button>

                <button type="button" @click="logout" class="logout-btn">退出登录</button>
            </div>
           
            <!--在线用户和群聊切换 -->
           <div class="middle-sidebar">
    <button type="button" @click="showList = 'onlineUsers'">在线用户</button>
    <button type="button" @click="showList = 'groups'">群聊列表</button>
    <div v-if="showList === 'onlineUsers'" class="online-user-list">
        <div v-for="user in onlineUsers" :key="user.username" @click="goToChat(user)" class="user-item">
            {{ user.username }}
            <span class="status-indicator" :class="{ 'online': user.isOnline }"></span>
        </div>
    </div>
    <div v-if="showList === 'groups'" class="group-list">
        <div v-for="group in groups" :key="group.id" @click="goToGroupChat(group)" class="group-item">
            {{ group.name }}
        </div>
    </div>
</div>

        </div>
    </div>
  <div v-if="showCreateGroupDialog" class="modal-overlay">
  <div class="modal">
    <h3 class="modal-title">创建群聊</h3>
    
    <input v-model="groupNameInput" placeholder="请输入群聊名称" class="modal-input" />

    <h4 class="modal-subtitle">选择初始成员</h4>
    <div class="modal-user-list">
      <div v-for="user in onlineUsers" :key="user.username">
        <label v-if="user && user.username !== currentUser" class="user-checkbox">
          <input type="checkbox" :value="user.username" v-model="selectedMembers" />
          {{ user.username }}
        </label>
      </div>
    </div>

    <div class="modal-buttons">
      <button class="confirm-btn" @click="sendCreateGroup">确认</button>
      <button class="cancel-btn" @click="cancelCreateGroup">取消</button>
    </div>
  </div>
</div>
<div v-if="showJoinGroupDialog" class="modal-overlay">
  <div class="modal">
    <h3 class="modal-title">加入群聊</h3>
    
    <input v-model="joinGroupNameInput" placeholder="请输入要加入的群聊名称" class="modal-input" />

    <div class="modal-buttons">
      <button class="confirm-btn" @click="sendJoinGroup">确认</button>
      <button class="cancel-btn" @click="cancelJoinGroup">取消</button>
    </div>
  </div>
</div>

</template>

<script>
import { useUserStore } from '@/stores/userStore'
import websocket from '@/services/websocket.js'
import { storePrivateMessage, getChatKey } from '@/stores/messageStorage'

export default {
    data() {
        const userStore = useUserStore()
        return {
            currentUser: userStore.username || '当前用户名',
            onlineUsers: [],
            groups: [],
            showList: 'onlineUsers',
            socket: null,
            onlineUsersTimer: null ,
            showCreateGroupDialog: false,
             groupNameInput: '',
            selectedMembers:[],
            showJoinGroupDialog: false,
joinGroupNameInput: '',

        };
    },
    mounted() {
        this.initWebSocket();
        // 添加定时器，每30秒请求一次在线用户列表
        this.onlineUsersTimer = setInterval(() => {
            if (this.socket && this.socket.readyState === WebSocket.OPEN) {
                this.requestOnlineUsers();
                this.requestGroupList();
            }
        }, 10000);
    },
    beforeUnmount() {
        if (this.socket) {
            this.socket.close();
        }
        // 清除定时器
        if (this.onlineUsersTimer) {
            clearInterval(this.onlineUsersTimer);
        }
    },
    methods: {
createGroup() {
   
  this.groupNameInput = '';
  this.selectedMembers = [];
  this.showCreateGroupDialog = true;
   console.log( this.showCreateGroupDialog);
},
 cancelCreateGroup() {
  this.showCreateGroupDialog = false;
},

  sendCreateGroup() {
  if (!this.groupNameInput.trim()) {
    alert('群聊名称不能为空');
    return;
  }

  const message = {
    messageType: 12, // GROUP_CREATE_REQUEST
    groupName: this.groupNameInput.trim(),
    sender: this.currentUser,
    members: [this.currentUser, ...this.selectedMembers]
  };

  if (this.socket && this.socket.readyState === WebSocket.OPEN) {
    this.socket.send(JSON.stringify(message));
    console.log('发送群聊创建请求:', message);
  }

  this.cancelCreateGroup();
},
joinGroup() {
  this.joinGroupNameInput = '';
  this.showJoinGroupDialog = true;
},

cancelJoinGroup() {
  this.showJoinGroupDialog = false;
},

sendJoinGroup() {
  if (!this.joinGroupNameInput.trim()) {
    alert('群聊名称不能为空');
    return;
  }

  const message = {
    messageType: 14, // GROUP_JOIN_REQUEST
    groupName: this.joinGroupNameInput.trim(),
    username: this.currentUser
  };
console.log(this.currentUser);
  if (this.socket && this.socket.readyState === WebSocket.OPEN) {
    this.socket.send(JSON.stringify(message));
    console.log('发送加入群聊请求:', message);
  }

  this.cancelJoinGroup();
},
requestGroupList() {
  if (this.socket && this.socket.readyState === WebSocket.OPEN) {
    const message = {
      messageType: 18, // GROUP_MY_LIST_REQUEST
      username: this.currentUser
    };
    this.socket.send(JSON.stringify(message));
    console.log('发送已加入群聊列表请求:', message);
  }
},
 logout() {
            const userStore = useUserStore();
            userStore.clearUser();
            
            if (this.socket) {
                this.socket.close();
            }
            
            this.$router.push({ name: 'login' });
            console.log('用户已成功退出登录');
        },
        goToChat(user) {
            // 不再传递socket对象
            this.$router.push({ 
                name: 'singleChat', 
                params: { 
                    friendName: user.username
                } 
            });
        },
         goToGroupChat(group) {
        // 传递群聊名称和当前的 WebSocket 实例
       this.$router.push({ name: 'groupChat', params: { groupId: group.name } });

    },
        initWebSocket() {
            this.socket = new WebSocket('ws://localhost:8080');
            
            this.socket.onopen = () => {
                console.log('WebSocket连接已建立');
                this.requestOnlineUsers();
                this.requestGroupList(); 
            };
            
            // 设置全局消息处理函数
            websocket.setGlobalMessageHandler((message) => {
                if (message.messageType === 4) {
                    storePrivateMessage(message);
                }
            });
            
            this.socket.onmessage = (event) => {
                try {
                    const data = event.data;
                    if (typeof data === 'string' && !data.startsWith('{')) {
                        console.warn('服务器返回消息:', data);
                        return;
                    }
                    
                    const message = JSON.parse(data);
                    switch (message.messageType) {
                        case 9: // ONLINE_RESPONSE类型
                            this.onlineUsers = message.onlineUsers.map(username => ({ 
                                username,
                                isOnline: true 
                            }));
                            break;
                        case 6: // 处理PING心跳响应
                            console.log('收到心跳响应');
                            break;
                        case 10: // 处理下线通知
                            console.log('用户下线:', message.username);
                            break;
                        case 4: // 私聊消息
                        case 11: // 私聊回复
                            storePrivateMessage(message);
                            break;
                        case 13: // GROUP_CREATE_RESPONSE
  if (message.success) {
    alert('群聊创建成功');
   /*  this.groups.push({ name: message.groupName, id: message.groupName }); */
  this.requestMyGroupList();
} else {
    alert('群聊创建失败: ' + message.reason);
  }
  break;
  case 15: // GROUP_JOIN_RESPONSE
  if (message.success) {
    alert('加入群聊成功');
    // 可选：添加到群聊列表
   /*  this.groups.push({ name: message.groupName, id: message.groupName }); */
   this.requestMyGroupList();
  } else {
    alert('加入群聊失败: ' + message.reason);
  }
  break;
  case 19: // GROUP_MY_LIST_RESPONSE
  if (Array.isArray(message.groups)) {
    this.groups = message.groups.map(groupName => ({
      id: groupName,
      name: groupName
    }));
    console.log('收到我的群聊列表:', this.groups);
  }
  break;
default:
     console.warn('收到未处理的消息类型:', message.messageType);
                    }
                } catch (error) {
                    console.error('消息解析错误:', error, '原始数据:', event.data);
                }
            };
        },
        requestOnlineUsers() {
            if (this.socket && this.socket.readyState === WebSocket.OPEN) {
                const message = {
                    messageType: 8, 
                    username: this.currentUser
                };
                this.socket.send(JSON.stringify(message));
            }
        }
    }
};

</script>

<style scoped>
.centered-container {
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #11998e, #38ef7d);
    position: absolute;
    top: 0;
    left: 0;
}

.main-wrapper {
    display: flex;
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.4);
    max-width: 1000px;
    height: 80vh;
}

.left-sidebar {
    width: 120px;
    background-color: #f0f2f5;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 10px;
    border-radius: 8px;
    margin-right: 20px;
}

.user-name {
    width: 100%;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    padding: 10px 0;
    color: #333;
    border-bottom: 1px solid #d9d9d9; 
}
.user-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin-bottom: 20px;
    border: 3px solid #66bb6a;
}

.left-sidebar button {
    width: 100%;
    padding: 12px 0;
    background-color: #1abc9c;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 15px;
    transition: all 0.3s ease;
}

.left-sidebar button:hover {
    background-color: #16a085;
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.middle-sidebar {
    width: 300px;
    padding: 10px;
    background-color: #f0f2f5;
    border-radius: 8px;
    overflow-y: auto;
    margin-left: 20px;
}

.middle-sidebar button {
    width: 100%;
    padding: 12px 0;
    background-color: #1abc9c;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 15px;
    transition: all 0.3s ease;
}

.middle-sidebar button:hover {
    background-color: #16a085;
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.friend-list, .group-list {
    margin-top: 10px;
}

.friend-item, .group-item {
    padding: 12px 15px;
    margin-bottom: 10px;
    background-color: white;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.friend-item:hover, .group-item:hover {
    background-color: #e8f5e9;
    transform: translateX(5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.chat-sidebar {
    flex: 1;
    background-color: white;
    border-radius: 8px;
    margin-left: 20px;
    padding: 20px;
    overflow-y: auto;
}

.logout-btn {
    margin-top: auto;
    margin-bottom: 0;
}

.online-user-list {
    margin-top: 10px;
}

.user-item {
    padding: 12px 15px;
    margin-bottom: 10px;
    background-color: white;
    border-radius: 6px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.user-item:hover {
    background-color: #e8f5e9;
    transform: translateX(5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.status-indicator {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #ccc;
}

.status-indicator.online {
    background-color: #4caf50;
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  padding: 24px;
  border-radius: 12px;
  width: 400px;
  max-height: 80vh;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
}

.modal-title {
  margin-bottom: 16px;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}

.modal-input {
  padding: 8px 12px;
  font-size: 16px;
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #ccc;
  width: 100%;
}

.modal-subtitle {
  margin-bottom: 8px;
  font-size: 16px;
}

.modal-user-list {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 16px;
  border: 1px solid #ddd;
  padding: 8px;
  border-radius: 6px;
}

.user-checkbox {
  display: block;
  margin-bottom: 6px;
  cursor: pointer;
}

.modal-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.confirm-btn, .cancel-btn {
  padding: 6px 14px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}

.confirm-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
}

.cancel-btn {
  background-color: #f44336;
  color: white;
  border: none;
}
</style>